package com.eeepay.eeepay_v2.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.NewsListAdapter;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.BaseGrpcTask;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.DBUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.NoticeApiServiceGrpc;
import cn.eeepay.api.grpc.nano.NoticeProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/22 0022.
 * 消息中心
 */
public class NewsCenterActivity extends ABBaseActivity implements AdapterView.OnItemClickListener, AbsListView.OnScrollListener {

    private ListView lv_content;
    private NewsListAdapter adapter;

    private int lastItem;
    private int page = 1;
    private int pageSize = 10;
    private int total;//消息总条数
    private boolean isFirst = true;

    private final static String IS_TOP = "top";//消息是否置顶

    private List<Map<String, String>> list = new ArrayList<>();//add by zhuangzeqin 2017年10月20日11:19:50 由updateUI提到前面来；否则每一次都会实例化一个对象

    @Override
    protected int getLayoutId() {
        return R.layout.activity_news_center;
    }

    @Override
    protected void initWidget() {
        lv_content = getViewById(R.id.lv_content);
        adapter = new NewsListAdapter(mContext);
        lv_content.setAdapter(adapter);

        sendHttpRequest(0);

    }

    @Override
    protected void eventOnClick() {
        lv_content.setOnItemClickListener(this);
        lv_content.setOnScrollListener(this);
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        super.sendHttpRequest(taskId);
        showProgressDialog();
        new GrpcTask().execute(Constant.URL.URL, Constant.URL.PORT);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        sendHttpRequest(0);
        adapter.notifyDataSetChanged();
    }

    /**
     * listView滑动状态改变的时候调用
     */
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        LogUtils.d("TAG", "lastItem=" + lastItem + " count=" + adapter.getCount());
        if (lastItem == adapter.getCount()
                && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            page++;
            LogUtils.d("TAG", "page = " + page);
            isFirst = false;
            if((page - 1) * pageSize < total){
                sendHttpRequest(0);
            }
        }
    }

    /**
     * listView滑动的时候调用
     * @param view
     * @param firstVisibleItem
     * @param visibleItemCount
     * @param totalItemCount
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        lastItem = firstVisibleItem + visibleItemCount;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        bundle.putString(Constant.TITLE,"消息详情");
        bundle.putString(Constant.INTENT_FLAG, Constant.NEWS_CENTER);
        bundle.putString(Constant.LINK, adapter.getDatas().get(position).get(Constant.LINK));
//        bundle.putString(Constant.NEWS_CONTENT, adapter.getItem(position).get(Constant.NEWS_CONTENT));
        SPUtils.put(Constant.NEWS_CONTENT,adapter.getItem(position).get(Constant.NEWS_CONTENT));
        goActivity(WebViewActivity.class, bundle);
        DBUtils.deleteById(adapter.getItem(position).get(Constant.USER_ID),
                adapter.getItem(position).get(Constant.NEWS_ID));
    }

    private class GrpcTask extends BaseGrpcTask<NoticeProto.NoticeMsgResponse>{

        @Override
        protected NoticeProto.NoticeMsgResponse doInBack(ManagedChannel channel) {
            NoticeApiServiceGrpc.NoticeApiServiceBlockingStub stub = NoticeApiServiceGrpc
                    .newBlockingStub(channel)
                    .withDeadlineAfter(30, TimeUnit.SECONDS);
            NoticeProto.NoticeRequest request = new NoticeProto.NoticeRequest();
            request.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
            request.oneAgentNo = UserInfo.getUserInfo2SP().getOneAgentNo();
            request.userId = UserInfo.getUserInfo2SP().getUserNo();
            request.pageNo = page;
            request.pageSize = pageSize;
            request.teamId = ConfigPorperties.getInstance().getTeamId();
            request.agentLevel = UserInfo.getUserInfo2SP().getAgentLevel();
            NoticeProto.NoticeMsgResponse response = stub.getNoticeInfo(request);
            return response;
        }

        @Override
        protected void updateUI(NoticeProto.NoticeMsgResponse result) {
            dismissProgressDialog();
            if(result != null){
                if(!result.resMsg.status){
                    showToast(result.resMsg.msg);
                    return;
                }
                list.clear();
                NoticeProto.NoticeMsg[] noticeMsgs = result.noticeMsg;
                NoticeProto.NoticeMsg[] topNoticeMsg = result.topNoticeMsg;//add by zhuangzeqin 2017年10月20日09:44:57 返回置顶的公告
                total = result.total;
                if (topNoticeMsg!=null && topNoticeMsg.length>0)//说明有置顶公告；如果有置顶公告直接追加到列表的头部
                {
                    total= total+topNoticeMsg.length;//累加置顶
                    for (int i = 0; i < topNoticeMsg.length; i++) {
                        if("false".equals(topNoticeMsg[i].ishistory)){//新消息
                            ContentValues cv = new ContentValues();
                            cv.put(Constant.USER_ID, UserInfo.getUserInfo2SP().getUserNo());
                            cv.put(Constant.NEWS_ID, topNoticeMsg[i].ntId);
                            LogUtils.d("news_id = " + topNoticeMsg[i].ntId);
                            DBUtils.insert(cv);
                        }

                        HashMap<String, String> map = new HashMap<>();
                        map.put(Constant.USER_ID, UserInfo.getUserInfo2SP().getUserNo());
                        map.put(Constant.NEWS_ID, topNoticeMsg[i].ntId);
                        Log.d("TID", "updateUI: "+topNoticeMsg[i].ntId);
                        map.put(Constant.NEWS_TITLE, topNoticeMsg[i].title);
                        map.put(Constant.NEWS_CONTENT, topNoticeMsg[i].content);
                        map.put(Constant.LINK, topNoticeMsg[i].link);
                        map.put(Constant.CREATE_TIME, topNoticeMsg[i].issuedTime);//add by zhuangzeqin 2017年10月24日11:19:57 创建时间改为下发时间
                        map.put(Constant.MESSAGE_IMG, topNoticeMsg[i].messageImg);
                        map.put(Constant.IS_HISTORY, topNoticeMsg[i].ishistory);
                        map.put(IS_TOP, "Y");
                        list.add(map);
                    }
                }
                //没有置顶公告的遍历
                if(noticeMsgs!=null && noticeMsgs.length > 0){
                    for (int i = 0; i < noticeMsgs.length; i++){
                        if("false".equals(noticeMsgs[i].ishistory)){//新消息
                            ContentValues cv = new ContentValues();
                            cv.put(Constant.USER_ID, UserInfo.getUserInfo2SP().getUserNo());
                            cv.put(Constant.NEWS_ID, noticeMsgs[i].ntId);
                            LogUtils.d("news_id = " + noticeMsgs[i].ntId);
                            DBUtils.insert(cv);
                        }

                        HashMap<String, String> map = new HashMap<>();
                        map.put(Constant.USER_ID, UserInfo.getUserInfo2SP().getUserNo());
                        map.put(Constant.NEWS_ID, noticeMsgs[i].ntId);
                        map.put(Constant.NEWS_TITLE, noticeMsgs[i].title);
                        map.put(Constant.NEWS_CONTENT, noticeMsgs[i].content);
                        map.put(Constant.LINK, noticeMsgs[i].link);
                        map.put(Constant.CREATE_TIME, noticeMsgs[i].issuedTime);
                        map.put(Constant.MESSAGE_IMG, noticeMsgs[i].messageImg);
                        map.put(Constant.IS_HISTORY, noticeMsgs[i].ishistory);
                        map.put(IS_TOP, "N");
                        list.add(map);
                    }
                }

                if(isFirst){
                    adapter.setList(list);
                }else{
                    adapter.addAll(list);
                }
            }
        }
    }
}
